#include <FileSystem/FAT32.h>
#include <FileSystem/FileAPI.h>
#include <FileSystem/Disk.h>
#include <IntExcept/Error.h>
#include <ProcessThread/ProcessThread.h>
#include <Memory/Heap.h>
#include <Kernel/GlobalData.h>

FAT32ENTRY GetFAT32Entry(const FAT32BPBHEADER* lpFAT32BPBHeader, DWORD dwIndex)
{
    DWORD dwBPBSecCnt = lpFAT32BPBHeader->BPB_ResvdSecCnt; /* BPB 占用的扇区数量 */
    DWORD dwClusSz = lpFAT32BPBHeader->BPB_BytsPerSec; /* 簇大小 */
    DWORD dwClusCnt = 2 + (lpFAT32BPBHeader->BPB_TotSec32 - dwBPBSecCnt - lpFAT32BPBHeader->BPB_FATSz32 * lpFAT32BPBHeader->BPB_NumFATs) / dwClusSz; /* 总簇数 */
    if (dwIndex < 2)
    {
        SetLastError(ERROR_ACCESS_DENIED);
        return FAT32_RESERVED;
    }
    if (dwIndex >= dwClusCnt)
    {
        SetLastError(ERROR_SECTOR_NOT_FOUND);
        return FAT32_RESERVED;
    }
    DWORD dwSecNum = dwBPBSecCnt + (dwIndex * 4) / 512; /* 该部分 FAT 所在的扇区 */
    DWORD dwOffs = dwIndex % 512;
    LPFAT32ENTRY FAT32EntArr = HeapAllocate(g_lpKernelHeap, HEAP_ZERO_MEMORY, 512); /* 从磁盘中读取一个扇区 */
    ReadDisk(FAT32EntArr, dwSecNum, 1);
    HeapFree(g_lpKernelHeap, FAT32EntArr);
    return FAT32EntArr[dwOffs];
}